Decimals 比 floats 要佔用更多記憶體:
import sys
from decimal import Decimal
a = 3.1415
b = Decimal('3.1415')
sys.getsizeof(a)
24
儲存 float 3.1415 需 24 bytes
sys.getsizeof(b)
104
然而 Decimal 3.1415 需要佔用 104 bytes。
Decimal 的數學運算也比 float 慢很多 (聽說在 GPU 上比 CPU 更明顯)
import time
from decimal import Decimal
def run_float(n=1):
for i in range(n):
a = 3.1415
def run_decimal(n=1):
for i in range(n):
a = Decimal('3.1415')
用上面兩個函式來計算兩者的運算速度:
n = 10000000
start = time.perf_counter()
run_float(n)
end = time.perf_counter()
print('float: ', end-start)
start = time.perf_counter()
run_decimal(n)
end = time.perf_counter()
print('decimal: ', end-start)
float: 0.12886674999026582
decimal: 0.884507458016742
可以看到生成一個 Decimal 物件遠比 float 物件花時間。
那加減乘除等等運算呢?來測試一下:
def run_float(n=1):
a = 3.1415
for i in range(n):
a + a
def run_decimal(n=1):
a = Decimal('3.1415')
for i in range(n):
a + a
start = time.perf_counter()
run_float(n)
end = time.perf_counter()
print('float: ', end-start)
start = time.perf_counter()
run_decimal(n)
end = time.perf_counter()
print('decimal: ', end-start)
float: 0.18404087499948218
decimal: 0.3708067910047248
速度差了兩倍左右。
最後來測試一下開根號:
(把 n 調低一點,因為⋯⋯)
n = 5000000
import math
def run_float(n=1):
a = 3.1415
for i in range(n):
math.sqrt(a)
def run_decimal(n=1):
a = Decimal('3.1415')
for i in range(n):
a.sqrt()
start = time.perf_counter()
run_float(n)
end = time.perf_counter()
print('float: ', end-start)
start = time.perf_counter()
run_decimal(n)
end = time.perf_counter()
print('decimal: ', end-start)
float: 0.20593712502159178
decimal: 6.594072999956552
Decimal 很慢,所以使用前也要三思,通常是為了精準度才會考慮用它。
好啦,我們明天見~
參考:Python 3: Deep Dive (Part 1 - Functional)